// user_mutex_multithread.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <pthread.h>
#include <string.h>

#define DEV_PATH "/dev/mutexdemo"

void *writer_thread(void *arg) {
    int fd = open(DEV_PATH, O_WRONLY);
    if (fd < 0) {
        perror("open writer");
        return NULL;
    }

    const char *messages[] = {
     "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n",
     "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n",
     "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC\n"
    };

    while (1) {
        for (int i = 0; i < 3; i++) {
            write(fd, messages[i], strlen(messages[i]));
            usleep(1000); // 50ms 间隔
        }
    }

    close(fd);
    return NULL;
}

void *reader_thread(void *arg) {
    int fd = open(DEV_PATH, O_RDONLY);
    if (fd < 0) {
        perror("open reader");
        return NULL;
    }

    char buf[128];

    while (1) {
        memset(buf, 0, sizeof(buf));
        lseek(fd, 0, SEEK_SET);  // 重置偏移
        read(fd, buf, sizeof(buf) - 1);
        printf("Read: %s", buf);
        usleep(20000);  // 70ms
    }

    close(fd);
    return NULL;
}

int main() {
    pthread_t tid1, tid2;

    // 启动写线程和读线程
    pthread_create(&tid1, NULL, writer_thread, NULL);
    pthread_create(&tid2, NULL, reader_thread, NULL);

    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);

    return 0;
}
